/*
* $Id: DatabaseManager.cpp 2 2009-12-23 13:58:02Z volok-aleksej@yandex.ru $
*
* Copyright 2008-2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "DatabaseManager.h"
#include "Database.h"

CDatabaseManager::CDatabaseManager(){}
CDatabaseManager::~CDatabaseManager()
{
	for(std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.begin(); it != m_aOpenDatabases.end(); it++)
		it->second->Free();
}

IDatabase* CDatabaseManager::OpenDatabase(const std::tstring& strNameDatabase)
{
	std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.find(strNameDatabase);
	if(it == m_aOpenDatabases.end()){
		CDatabase* pDatabase = new CDatabase(strNameDatabase);
		pDatabase->Open();
		it = m_aOpenDatabases.insert(m_aOpenDatabases.begin(), std::make_pair(DatabaseHandle(strNameDatabase), pDatabase)); 
	}
	else
		((int)(it->first.m_nClient))++;
	return it->second;
}

void CDatabaseManager::CloseDatabase(IDatabase* pDatabase)
{
	std::map<DatabaseHandle, IDatabase*>::iterator it = m_aOpenDatabases.find(pDatabase->GetDatabaseName());
	if(it != m_aOpenDatabases.end())
	{
		if(it->first.m_nClient == 0)
		{
			it->second->Free();
			m_aOpenDatabases.erase(it);
		}
		else
			((int)(it->first.m_nClient))--;
	}
}

void CDatabaseManager::Free()
{
	delete this;
}
void CDatabaseManager::Initialize(){
	
}